<?php

// +----------------------------------------------------------------------
// | EasyAdmin
// +----------------------------------------------------------------------
// | PHP交流群: 763822524
// +----------------------------------------------------------------------
// | 开源协议  https://mit-license.org
// +----------------------------------------------------------------------
// | github开源项目：https://github.com/zhongshaofa/EasyAdmin
// +----------------------------------------------------------------------

namespace app\common\model;

use think\Model;
use think\facade\Db;
use app\api\model\Yjcomm;
/**
 *今日业绩
 * Class TimeModel
 * @package app\common\model
 */
class TodaysModel extends Model
{
    public function __construct()
    {
        $this->Yjcomm=new Yjcomm();
    }
    /**
     * 统计流水（实收金额） function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2021-01-26
     * @param [type] $store_id 店铺id
     * @param [type] $start_time 开始时间
     * @param [type] $end_time  结束时间
     * @param [type] $pay_method 支付方式  【1-扫码支付2-现金支付3-小程序支付（用户自行支付）4-会员储值卡支付 5-挂账(统计已结算的) 6-微信 7-支付宝】
     * @param [type] $type  1:实收  2：应收
     * @return void
     */
    public function getAllWaterCount($store_id,$start_time,$end_time,$pay_method,$type=1){
        $where=[
            
            ['store_id','=',$store_id],
            ['orders_status','not in',[0]],
            ['pay_method','=',$pay_method],
            ['delete_time','=',0]
        ];
        //储值卡
        $weh = [
            ['store_id', '=', $store_id],
            ['order_type', '=', 4],
            ['order_status', '>=', 0],
            ['complete_time', 'between', [$start_time, $end_time]],
            ['pay_way', '=', $pay_method],

        ];
       
        $record = Db::name('mid_orders')->where($weh)->column('order_id');
        $card_gift_admout=0;
        if($record){
            $card_gift_list = Db::name('member_gift_card')->whereIn('id', $record)->where('otype', 1)->field('amount*num as total')->select()->toArray();
         
            $card_gift_admout = array_sum(array_column($card_gift_list, 'total'));
        }
         //储值卡结束
      
        $card_amount=0;
        if ($pay_method==5) {
            $teemp=['is_settlement','=',1];
            array_push($where,['closetime','between',"$start_time,$end_time"]);
        
            array_push($where,$teemp);
            
            $card_amount=$this->getPackageCardAmount($store_id, $start_time, $end_time, $pay_method);
        }else{
            array_push($where,['orders_create_time','between',"$start_time,$end_time"]); 
        }
        if($type==1){
            $field="act_price";
        }else{
            $field="sum_price";
        }
        $orders_id= Db::name('orders')-> where($where)-> column('orders_id');
        if($orders_id){
            $orders_id=implode(',',$orders_id);
        }
     
        $amount=Db::name('orders_server')->whereIn('orders_id',$orders_id)->sum($field);
   
        $memberprice=$this->getMemberRecharge($store_id,$start_time,$end_time,$pay_method);
        if($pay_method==5){
            if($memberprice)$memberprice['charge'] = 0;
        }
        if($memberprice){
            return number_format($amount + $memberprice['charge']+ $card_amount+ $card_gift_admout, 2);
        }else{
            return number_format($amount+ $card_amount+ $card_gift_admout, 2);
        }
        
    }
    //获取年卡挂账金额
    public function getPackageCardAmount($store_id, $start_time, $end_time, $pay_method,$state=1){
        $whereCard = [
            ['is_settlement', '=', 1],
            ['is_pay', '=', 1],
            ['pay_method', '=', $pay_method],
            ['delete_time', '=', 0]
        ];
        $card_amount=0;
        if($pay_method==5){
            array_push($whereCard, ['closetime', 'between', "$start_time,$end_time"]);
            $card_ids = Db::name('card')->where('store_id', $store_id)->column('id');
            array_push($whereCard, ['card_id', 'in', $card_ids]);
            if($state==1){
                $card_amount = Db::name('package_card')->where($whereCard)->sum('amount');
            }else{
                $card_amount = Db::name('package_card')->where($whereCard)->select()->toArray();
            }
           
        }
        return $card_amount;
    }
    /**
     * 统计订单总的应收和实收金额 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-20
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @param [type] $type  1:实收 2：应收
     * @return void
     */
    public function getReceivable($store_id,$start_time,$end_time,$type){
        $pay_method=[1,2,3,6,7];
        if($type==1){
          
            $field="act_price";
        }else{
            $field="sum_price";
        }
        $where=[
            ['orders_create_time','between',"$start_time,$end_time"],
            ['store_id','=',$store_id],
            ['orders_status','not in',[0]],
            ['delete_time','=',0]
        ];
        $whereFive = [
            ['closetime', 'between', "$start_time,$end_time"],
            ['store_id', '=', $store_id],
            ['orders_status', 'not in', [0]],
            ['delete_time', '=', 0],
            ['pay_method', '=', 5],
            ['is_settlement','=',1]
        ];
        $chargeorderIds= Db::name('orders') -> where($whereFive)-> column('orders_id');//挂账订单
         array_push($where, ['pay_method','in',$pay_method]);
        $orders_id= Db::name('orders')-> where($where)-> column('orders_id');
        
        if($chargeorderIds){
            $orders_id= array_merge($orders_id,$chargeorderIds);
        }
        if($orders_id){
            $orders_id=implode(',',$orders_id);
        }
       
        $receivable =Db::name('orders_server')->whereIn('orders_id',$orders_id)->sum($field);
        $memberprice=$this->getMemberRecharge($store_id,$start_time,$end_time);
        $card_amount = $this->getPackageCardAmount($store_id, $start_time, $end_time, 5);
        //储值卡
        $weh = [
            ['store_id', '=', $store_id],
            ['order_type', '=', 4],
            ['order_status', '>=',0],
            ['complete_time', 'between', [$start_time, $end_time]],

        ];

        $record = Db::name('mid_orders')->where($weh)->column('order_id');
        $card_gift_admout = 0;
        if ($record) {
            $card_gift_list = Db::name('member_gift_card')->whereIn('id', $record)->where('otype', 1)->field('amount*num as total')->select()->toArray();
            $card_gift_admout = array_sum(array_column($card_gift_list,'total'));
        }
        
        if($memberprice){
            return $receivable + $memberprice['charge']+ $card_amount+ $card_gift_admout;
        }else{
            return $receivable+ $card_amount + $card_gift_admout;
        }
        
        // return number_format($receivable+$memberprice['charge'],2);
    }
    /**
     * 消费统计 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-20
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @return void
     */
    public function getConsumptionStatistics($store_id,$start_time,$end_time,$type){
        $where=[
            ['orders_create_time','between',"$start_time,$end_time"],
            ['store_id','=',$store_id],
            ['orders_status','not in',[0]],
            ['delete_time','=',0]
        ];
        $orders_id= Db::name('orders')-> where($where)-> column('orders_id');
     
        if($orders_id){
            $orders_id=implode(',',$orders_id);
        }
       
        $order_server_where=[['orders_id','in',$orders_id]];
        if($type==1){
            $orders_server_arr_tmp =Db::name('orders_server') 
            -> field('server_id,type as server_type,sum(act_price) as sub_total, count(*) as count') 
            -> where($order_server_where) 
            -> group('server_id,type') 
            -> select()->toArray();
            
            $cate_tmp=[];
            if($orders_server_arr_tmp){
                // $this->Yjcomm->getImage($store_id,$value['server_type'],$value['server_id']);
                foreach ($orders_server_arr_tmp as $key => $value) {
                    if($value['server_type']==1 || $value['server_type']==0){
                       $pidname= $this->Yjcomm-> getPidName($store_id,$value['server_id']);
                       
                        $cateInfo['cate_name']= $pidname?$pidname['cate_name']:"";
                        $cateInfo['cate_id']= $pidname?$pidname['store_category_id']:"";
                    }elseif($value['server_type']==2){
                        $cateInfo['cate_name']="套餐服务";
                        $cateInfo['cate_id']=2;
                    }elseif($value['server_type']==3){
                        $cateInfo['cate_name']="汽车饰品";
                        $cateInfo['cate_id']=3;
                    } elseif ($value['server_type'] == 5) {
                        $cateInfo['cate_name'] = "积分兑换";
                        $cateInfo['cate_id'] = 555;
                    } elseif ($value['server_type'] == 4) {
                        $cateInfo['cate_name'] = "积分兑换优惠券";
                        $cateInfo['cate_id'] = 666;
                    }
                    if($cateInfo){
                            $cate_tmp[$key]['cate_name']    = $cateInfo['cate_name'];
                            $cate_tmp[$key]['cate_id']      = $cateInfo['cate_id'];
                            $cate_tmp[$key]['sub_total']    = $value['sub_total'];
                            $cate_tmp[$key]['server_type']  = $value['server_type'];
                            $cate_tmp[$key]['count']        = $value['count']; 
                    }
                    
                }
                
            }
            //储值卡
            $weh = [
                    ['store_id', '=', $store_id],
                    ['order_type', '=', 4],
                    ['order_status', '>=', 0],
                    ['complete_time', 'between', [$start_time, $end_time]],

                ];

            $record = Db::name('mid_orders')->where($weh)->column('order_id');
            $card_gift_admout = 0;
            $card_gift_lists=[];
            if ($record) {
                $card_gift_list = Db::name('member_gift_card')->whereIn('id', $record)->where('otype', 1)->field('amount*num as total')->select()->toArray();
                $card_gift_admout = array_sum(array_column($card_gift_list, 'total'));
                $card_gift_lists[]=[
                    'count'=>count($record),
                    'cate_name'=>'储值卡',
                    'cate_id'=>666,
                    'server_type'=>6,
                    'sub_total'=> $card_gift_admout,
                ];
            }
         //储值卡结束
            $result = [];
            if($cate_tmp){
                if($cate_tmp){
                    $cate_names = array_unique(array_column($cate_tmp, 'cate_name'));
                    if($cate_names){
                        foreach ($cate_names as $k => $cate_name) {
                            $sum = 0;
                            $count = 0;
                            foreach ($cate_tmp as $indx => $item) {
                                if ($item['cate_name'] == $cate_name) {
                                    $count = $count + $item['count'];
                                    $result[$k]['count'] = $count;
                                    $result[$k]['cate_name'] = $cate_name;
                                    $result[$k]['cate_id'] = $item['cate_id'];
                                    $result[$k]['server_type'] = $cate_name == "美容服务" ? 1 : $item['server_type'];
                                    $sum = $sum + $item['sub_total'];
                                    $result[$k]['sub_total'] = sprintf("%.2f", $sum);
                                }
                            }
                        }
                    }
                   
                }
                if($result)$result=array_merge($result);
            }
            if($card_gift_lists && $result){
                $result=array_merge($result, $card_gift_lists);
            }elseif($card_gift_lists && !$result){
                $result = array_merge($result);
            }
        }else{
            $result =Db::name('orders_server') -> where($order_server_where) ->sum('sum_price');
        }
       
        return $result;
    }
    /**
     * 总消费 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-20
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @param [type] $type
     * @return void
     */
    public function getTotalPrice($store_id,$start_time,$end_time,$type=1){
        $where=[
            ['orders_create_time','between',"$start_time,$end_time"],
            ['store_id','=',$store_id],
            ['orders_status','not in',[0]],
            ['delete_time','=',0]
        ];
        if($type==2){//会员卡消费统计
            array_push($where,['pay_method','=',4]);
        }
        //储值卡
        $weh = [
            ['store_id', '=', $store_id],
            ['order_type', '=', 4],
            ['order_status', '>=', 0],
            ['complete_time', 'between', [$start_time, $end_time]],

        ];

        $record = Db::name('mid_orders')->where($weh)->column('order_id');
        $card_gift_admout = 0;
        if ($record) {
            $card_gift_list = Db::name('member_gift_card')->whereIn('id', $record)->where('otype', 1)->field('amount*num as total')->select()->toArray();
            $card_gift_admout = array_sum(array_column($card_gift_list, 'total'));
        }
         //储值卡结束
        $amount= Db::name('orders')-> where($where)-> sum('amount');
        return  $amount+$card_gift_admout;
                 
    }
    /**
     * 挂账实收 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-20
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @return void
     */
    public function getBuyer($store_id,$start_time,$end_time,$type=1){
        $where=[
            ['orders_create_time','between',"$start_time,$end_time"],
            ['store_id','=',$store_id],
            ['orders_status','not in',[0]],
            ['delete_time','=',0]
            
        ];
        if($type==1){
            array_push($where,['pay_method','=',5]);
        }
        $orderIds=Db::name('orders')->where($where)->fetchSql(false)-> column('orders_id');
        $receipts = Db::name('orders_server')->whereIn('orders_id',$orderIds)->sum('act_price');//实收
        return $receipts;
    }
    /**
     * 支付方式,消费查详情 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-12
     * @param [type] $store_id  店铺id
     * @param [type] $pay_method  支付方式  【1-扫码支付2-现金支付3-小程序支付（用户自行支付）4-会员储值卡支付 5-挂账(统计已结算的) 6-微信 7-支付宝】
     * @param [type] $page 页码
     * @param [type] $size  数量
     * @param [type] $start_time 开始时间
     * @param [type] $end_time    结束时间
     * @return void
     */
    public function payWay($store_id,$pay_method,$start_time,$end_time,$page,$size){
        
        $where=[
          
            ['store_id','=',$store_id],
            ['orders_status','not in',[0]],
            ['delete_time','=',0]
        ];
        if ($pay_method==5) {
         
            array_push($where,['closetime','between',"$start_time,$end_time"]);
         
        }else{
            array_push($where,['orders_create_time','between',"$start_time,$end_time"]); 
        }
        if(is_array($pay_method)){
            array_push($where,['pay_method','in',$pay_method]);
        }else{
            array_push($where,['pay_method','=',$pay_method]);
        }
        //储值卡
        $weh = [
            ['store_id', '=', $store_id],
            ['order_type', '=', 4],
            ['order_status', '>=', 0],
            ['complete_time', 'between', [$start_time, $end_time]],

        ];
        if (is_array($pay_method)) {
            array_push($weh, ['pay_way', 'in', $pay_method]);
        } else {
            array_push($weh, ['pay_way', '=', $pay_method]);
        }
        $record = Db::name('mid_orders')->where($weh)->column('order_id');
        $card_gift_lists = [];
        if ($record) {
            $card_gift_lists = Db::name('member_gift_card')->whereIn('id', $record)->where('otype', 1)->field('id,amount,out_trade_no,gift_card_id,num')->select()->toArray();
        }
        $card_gift_lists_relust=[];
        if($card_gift_lists){
            foreach ($card_gift_lists as $k => $v) {
                $card_gift_lists_relust[]=[
                    'orders_id' => $v['id'],
                    'server_id' => $v['gift_card_id'],
                    'attr' => '轿车',
                    'sum_price' => $v['amount']*$v['num'],
                    'act_price' => $v['amount'] * $v['num'],
                    'type' => 4,
                    'table_name' => 'member_gift_card',
                    'server_name' => Db::name('gift_card')->where('id', $v['gift_card_id'])->value('name'),
                    'out_trade_no' => $v['out_trade_no']
                ];
            }
        }
         //储值卡结束
        $orderIds=Db::name('orders')->where($where)->fetchSql(false)-> column('orders_id');
     
        $order_where=[
            ['orders_id','in',$orderIds]
        ];
        $orders = Db::name('orders_server') 
        -> field('orders_id,server_id,attr,sum_price,act_price,type')
        -> where($order_where) ->page($page,$size)-> select()->toArray();
        if($orders){
            foreach ($orders as $k => $v) {

                $server_name = $this->Yjcomm->getTitle($store_id, $v['type'], $v['server_id']);
                $orders[$k]['server_name'] = $server_name ? $server_name : '';
                $orders[$k]['table_name'] = "orders";
                $orders[$k]['out_trade_no'] = Db::name('orders')->where('orders_id', $v['orders_id'])->value('out_trade_no');
            }
        } 
        $total=Db::name('orders_server') -> where($order_where) -> count();
        $memberOrders=$this->getMemberRechargeOrders($store_id,$pay_method,$start_time,$end_time,$page,$size);
        if($memberOrders){
            // $orders = array_merge($orders,$memberOrders);
            $total+=$memberOrders['total'];
        }
        $cardOrdersLists=[];
       
        $card_lists= $this->getPackageCardAmount($store_id, $start_time, $end_time, $pay_method,2);
        if($card_lists){
            foreach ($card_lists as $k => $v) {
                $cardOrdersLists=[
                    'orders_id'=>$v['id'],
                    'server_id'=>$v['card_id'],
                    'attr'=>'轿车',
                    'sum_price'=>$v['amount'],
                    'act_price'=>$v['amount'],
                    'type'=>3,
                    'table_name'=>'package_card',
                    'server_name'=>Db::name('card')->where('id',$v['card_id'])->value('name'),
                    'out_trade_no'=>$v['out_trade_no']
                ];
            }
            if ($cardOrdersLists) {
                array_push($orders, $cardOrdersLists);
            }
        }
        if($card_gift_lists_relust && $orders){
            $orders=array_merge($orders, $card_gift_lists_relust);
        }elseif ($card_gift_lists_relust && !$orders) {
            $orders = array_merge($card_gift_lists_relust);
        }
        $array=[
            'total'=>$total,
            'lists'=>$orders,
            'record2'=>$memberOrders['record2']
         ];
        
        return $array;
    }
   
    /**
     * 消费统计服务列表 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-21
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @param [type] $server_type
     * @param [type] $cate_id
     * @param [type] $page
     * @param [type] $size
     * @return void
     */
    public function getOrders($store_id,$start_time,$end_time,$server_type='',$cate_id='',$page,$size,$company_id='',$pay_method=''){
        $where=[
            ['orders_create_time','between',"$start_time,$end_time"],
            ['store_id','=',$store_id],
            ['orders_status','not in',[0]],
            ['delete_time','=',0]
        ];
        if($company_id){
            array_push($where,['company_id','=',$company_id]);
        }
        if($pay_method){
            array_push($where,['pay_method','=',$pay_method]);
        }
        $orderIds=Db::name('orders')->where($where)->fetchSql(false)-> column('orders_id');
       
        $order_where=[
            ['orders_id','in',$orderIds],
            
        ];
        if($server_type==0){
            $xiche=Db::name('store_category')->where('store_category_id',$cate_id)->find();
            if($xiche){
                if ($xiche['cate_id'] == 23) {
                    $aacateid = Db::name('store_category')->where('pid', $xiche['store_category_id'])->column('store_category_id');
                    array_push($order_where, ['server_id', 'in', $aacateid]);
                }
            }
            
           
        }
        if($server_type && !in_array($server_type,[2,3])){
            if($cate_id == 555 && $server_type==5){

            }else{
                $xiche = Db::name('store_category')->where('store_category_id', $cate_id)->find();
                if ($xiche) {
                    if ($xiche['cate_id'] == 2) {
                        $aacateid = Db::name('store_category')->where('pid', $xiche['store_category_id'])->column('store_category_id');
                        array_push($order_where, ['server_id', 'in', $aacateid]);
                    } elseif ($xiche['cate_id'] == 1) {
                        $aacateid = Db::name('store_category')->where('pid', $xiche['store_category_id'])->column('store_category_id');
                        array_push($order_where, ['server_id', 'in', $aacateid]);
                    } else {
                        $xiche = Db::name('store_category')->where('store_category_id', $cate_id)->find();
                        $aacateid = Db::name('store_category')->where('pid', $xiche['store_category_id'])->column('store_category_id');
                        if ($aacateid) {
                            array_push($order_where, ['server_id', 'in', $aacateid]);
                        } else {
                            array_push($order_where, ['server_id', '=', $cate_id]);
                        }
                    }
                }
            }
            
            
            
        }
       if($server_type){
          array_push($order_where,['type','=',$server_type]);
       }
       
        $orders = Db::name('orders_server') 
        -> field('orders_id,server_id,attr,sum_price,act_price,type as order_type')
        -> where($order_where) ->page($page,$size)-> select()->toArray();
        if($orders){
            foreach ($orders as $key => $v) {
                $server_name = $this->Yjcomm->getTitle($store_id, $v['order_type'] == 0 ? 1 : $v['order_type'], $v['server_id']);
                $orders[$key]['server_name'] = $server_name;
                $orders[$key]['out_trade_no'] = Db::name('orders')->where('orders_id', $v['orders_id'])->value('out_trade_no');
                $orders[$key]['type']=Db::name('mid_orders')->where('order_id', $v['orders_id'])->value('order_type');
            }
        }
        //储值卡
        $weh = [
            ['store_id', '=', $store_id],
            ['order_type', '=', 4],
            ['order_status', '>=', 0],
            ['complete_time', 'between', [$start_time, $end_time]],

        ];

        $record = Db::name('mid_orders')->where($weh)->column('order_id');
        $card_gift_lists = [];
        if ($record) {
            $card_gift_lists = Db::name('member_gift_card')->whereIn('id', $record)->where('otype', 1)->field('id,amount,out_trade_no,gift_card_id,num')->select()->toArray();
        }
        $card_gift_lists_relust = [];
        if ($card_gift_lists) {
            foreach ($card_gift_lists as $k => $v) {
                $card_gift_lists_relust[] = [
                    'orders_id' => $v['id'],
                    'server_id' => $v['gift_card_id'],
                    'attr' => '轿车',
                    'sum_price' => $v['amount']*$v['num'],
                    'act_price' => $v['amount'] * $v['num'],
                    'order_type' => 4,
                    'out_trade_no' => $v['out_trade_no'],
                    'server_name' => Db::name('gift_card')->where('id', $v['gift_card_id'])->value('name'),
                ];
            }
        }
        //储值卡结束
        if ($card_gift_lists_relust && $orders) {
            $orders = array_merge($orders, $card_gift_lists_relust);
        } elseif ($card_gift_lists_relust && !$orders) {
            $orders = array_merge($card_gift_lists_relust);
        }
        return $orders;
    }
    /**
     * 挂账统计 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-13
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @return void
     */
    public function GetOnaccount($store_id,$start_time,$end_time){
        $company=Db::name('company')->field('id,title')->where('store_ids','like','%'.$store_id.'%')->select()->toArray();
      
        if($company){
            foreach ($company as $k => $v) {
                $aa=$this->getCompanyTotal($store_id,$start_time,$end_time,$v['id']);
                if($aa){
                    $company[$k]['count'] = $aa[0]['count'];
                    $company[$k]['sub_total'] = $aa[0]['sub_total'] ? $aa[0]['sub_total'] : 0;
                }else{
                    $company[$k]['count'] = 0;
                    $company[$k]['sub_total'] = 0;
                }
                
            }
        }
        $where=[
            ['pay_method','=',5],
            ['orders_status','not in',[0]],
            ['orders_create_time','between',[$start_time,$end_time]],
            ['store_id','=',$store_id],
            ['delete_time','=',0]

        ];
        $orderIds=Db::name('orders')->where($where)->fetchSql(false)-> column('orders_id');
        if($orderIds){
            $orderIds=implode(',',$orderIds);
        }
        $receivable =Db::name('orders_server')->field('SUM(sum_price) as sum_price,SUM(act_price) as act_price')->whereIn('orders_id',$orderIds)->select()->toArray();//应收
        if($receivable){
            $data['receipts'] = number_format(array_sum(array_column($receivable, 'act_price')), 2);
            $data['receivable'] = number_format(array_sum(array_column($receivable, 'sum_price')), 2);
            $data['total_price'] = number_format(array_sum(array_column($receivable, 'act_price')), 2);
        }else{
            $data['receipts'] = 0.00;
            $data['receivable'] = 0.00;
            $data['total_price'] = 0.00;
        }
        
        $data['lists']=$company;
        return $data;
    }
     /**
     * 挂账公司下的单数和金额 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2021-05-18
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @param [type] $company_id
     * @return void
     */
    public function getCompanyTotal($store_id,$start_time,$end_time,$company_id){
        $where=[
            ['pay_method','=',5],
            ['orders_status','not in',[0]],
            ['orders_create_time','between',[$start_time,$end_time]],
            ['store_id','=',$store_id],
            ['company_id','=',$company_id],
            ['delete_time','=',0]

        ];
        $orders_id= Db::name('orders')->where($where)->fetchSql(false) -> column('orders_id');
        $orders_server_arr_tmp=[];
        if($orders_id){
            $orders_server_arr_tmp = Db::name('orders_server')
            ->field('sum(act_price) as sub_total, count(*) as count')
            ->whereIn('orders_id', $orders_id)
            ->fetchsql(false)
            ->select()->toArray();
        }
        
        return $orders_server_arr_tmp;
    }
    /**
     * 会员充值记录 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-21
     * @param [type] $store_id
     * @param [type] $pay_method
     * @param [type] $start_time
     * @param [type] $end_time
     * @param [type] $page
     * @param [type] $size
     * @return void
     */
    public function getMemberRechargeOrders($store_id,$pay_method,$start_time,$end_time,$page,$size){
        $weh=[
            ['store_id','=',$store_id],
            ['is_end','=',1],
            ['order_type','=',2],
            ['complete_time','between',[$start_time,$end_time]],
          
        ];
        if($pay_method)  array_push($weh,['pay_way','=',$pay_method]);
        $record = Db::name('mid_orders') -> where($weh) ->page($page, $size)-> select()->toArray();
  
        $total=Db::name('mid_orders') -> where($weh)->count();
        $record2 = [];
       if($record){
            foreach ($record as $key => $value) {
                $record2[$key]['out_trade_no'] = $value['out_trade_no'];
                $record2[$key]['id'] = $value['mid'];
                $record2[$key]['act_price'] = $value['commission']+$value['shop_money'];
                $record2[$key]['server_name'] = "会员充值";
                $record2[$key]['table_name'] = "mid_orders";
               
            }
       }
       return [
            'record2'   =>$record2,
            'total'     =>$total,
       ];
    }
    /**
     * 会员充值 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-20
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @return void
     */
    public function getMemberRecharge($store_id,$start_time,$end_time,$pay_method=''){
        $interests=0;
        $charge=0;
        $weh=[
            ['store_id','=',$store_id],
            ['is_end','=',1],
            ['order_type','=',2],
            ['complete_time','between',[$start_time,$end_time]],
          
        ];
        if($pay_method)  array_push($weh,['pay_way','=',$pay_method]);
        $record = Db::name('mid_orders') -> where($weh) -> select()->toArray();
        if($record){
            foreach ($record as $key => $value) {
                $charge += $value['commission'];
                $charge += $value['shop_money'];
            }
            $interests += count($record);
        }
        
       
       return [
            'charge'   =>$charge,
            'interests'=>$interests,
       ];
    }
    /**
     * 会员储值和会员消费 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2021-01-26
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @return void
     */
    public function getCrecords($store_id,$start_time,$end_time){
        $record = $this->getMemberRecharge($store_id,$start_time,$end_time);
        $interests=$record['interests'];
        $charge=$record['charge'];
       $where=[
            ['pay_method','=',4],
            ['orders_status','not in',[0]],
            ['orders_create_time','between',[$start_time,$end_time]],
            ['store_id','=',$store_id],
            ['delete_time', '=', 0]

        ];
        $orderIds=Db::name('orders')->where($where)->fetchSql(false)-> column('orders_id');
   
        $memberscount=0;
        if($orderIds){
            $memberscount=Db::name('orders_server')->whereIn('orders_id',$orderIds)->count();
            
        }
        $total_price=$this->getTotalPrice($store_id,$start_time,$end_time,2);
        $yaerwhere=[
            ['use_time', 'between', [$start_time, $end_time]],
            ['store_id', '=', $store_id],
            ['out_trade_no', '>', 0],
        ];
        $year=Db::name('used_card_record')->where($yaerwhere)->count();
        $cate_records[0]['cate_name']="会员卡消费";
        $cate_records[0]['count']=$memberscount;
        $cate_records[0]['sub_total']=$total_price;
        $cate_records[1]['cate_name']="会员卡储值";
        $cate_records[1]['count']=$interests;
        $cate_records[1]['sub_total']=$charge;
        $cate_records[2]['cate_name'] = "年卡消费";
        $cate_records[2]['count'] = $year;
        $cate_records[2]['sub_total'] = 0;
        $data=[
            'lists'        =>$cate_records,
            'charge'       =>sprintf("%.2f",$charge),//会员卡充值
            'receipts'     =>sprintf("%.2f",$total_price),//会员卡消费
            'total_price'  =>sprintf("%.2f",$total_price),//消费总金额
        ];
     
        return $data;
    }
    /**
     * 年卡支付明细 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-12-27
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @param [type] $page
     * @param [type] $size
     * @return void
     */
    public function getYearDetail($store_id, $start_time, $end_time, $page, $size)
    {
        $yaerwhere = [
            ['use_time', 'between', [$start_time, $end_time]],
            ['store_id', '=', $store_id],
            ['out_trade_no', '>', 0],
        ];
        $out_trade_no = Db::name('used_card_record')->where($yaerwhere)->page($page, $size)->column('out_trade_no');
        $where=[
            ['out_trade_no','in', $out_trade_no]
        ];
        $orderIds = Db::name('orders')->where($where)->fetchSql(false)->column('orders_id');

        $order_where = [
            ['orders_id', 'in', $orderIds],

        ];
        $orders = Db::name('orders_server')
        ->field('orders_id,server_id,attr,sum_price,act_price,type')
        ->where($order_where)->page($page, $size)->select()->toArray();
        if ($orders) {
            foreach ($orders as $key => $v) {
                $server_name = $this->Yjcomm->getTitle($store_id, $v['type'] == 0 ? 1 : $v['type'], $v['server_id']);
                $orders[$key]['server_name'] = $server_name;
                $orders[$key]['out_trade_no'] = Db::name('orders')->where('orders_id', $v['orders_id'])->value('out_trade_no');
            }
        }

        return $orders;
    }
    /**
     * 卡金额统计 function
     *
     * @Author YJ 991850594@qq.com
     * @DateTime 2022-04-20
     * @param [type] $store_id
     * @param [type] $start_time
     * @param [type] $end_time
     * @return void
     */
    public function getCardPrice($store_id,$start_time,$end_time){
        $card_ids=Db::name('card')->where('store_id',$store_id)->column('id');
        $where=[
            ['is_pay','=',1],
            ['create_time','between',[$start_time,$end_time]],
            ['card_id','in',$card_ids],
        ];
        $amount=Db::name('package_card')->where($where)->sum('amount');
        return $amount;
    }
     /**
      * 卡统计 function
      *
      * @Author YJ 991850594@qq.com
      * @DateTime 2022-04-20
      * @param [type] $store_id
      * @param [type] $start_time
      * @param [type] $end_time
      * @return void
      */
     public function getCard($store_id,$start_time,$end_time){
         $card_ids=Db::name('card')->where('store_id',$store_id)->column('id');
        $where=[
            ['is_pay','=',1],
            ['create_time','between',[$start_time,$end_time]],
            ['card_id','in',$card_ids],
        ];
        $package_card=Db::name('package_card')->where($where)->field('card_id,sum(amount) as amount,count(*) as number')->group('card_id')->select()->toArray();
        
        $total=array_sum(array_column($package_card,'amount'));
        $receivable=0;
        $result=[];
        if($package_card){
            foreach ($package_card as $k => $v) {
                $card_name=Db::name('card')->where('id',$v['card_id'])->value('name');
                if($v['amount']>0){
                    $result[]=array(
                        'card_name' =>$card_name,
                        'amount'    =>$v['amount'],
                        'number'    =>$v['number'],
                        'card_id'   =>$v['card_id']
                    );
                }
            }
        }
        $data['receipts']=sprintf("%.2f",$total);
        $data['receivable']=$receivable==0?sprintf("%.2f",$total):sprintf("%.2f",$receivable);
        $data['total_price']=sprintf("%.2f",$total);
        $data['lists']=$result;
        return $data;
    }
}
